package com.wechar_rpa.controller;

import com.wechar_rpa.model.ChatMessage;
import com.wechar_rpa.service.ChatMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/messages")
public class ChatMessageController {

    @Autowired
    private ChatMessageService chatMessageService;

    @PostMapping("/save")
    public ChatMessage saveChatMessage(@RequestBody Map<String, Object> payload) {
        ChatMessage message = new ChatMessage();

        message.setUserId((String) payload.get("userId"));
        message.setUsername((String) payload.get("username"));
        message.setContent((String) payload.get("content"));
        message.setTimestamp(payload.containsKey("timestamp") ? (Date) payload.get("timestamp") : new Date());
        message.setWhitelisted((Boolean) payload.get("isWhitelisted"));

        // 群聊相关字段
        if (payload.containsKey("groupId")) {
            message.setGroupId((String) payload.get("groupId"));
        }
        if (payload.containsKey("groupName")) {
            message.setGroupName((String) payload.get("groupName"));
        }
        if (payload.containsKey("isGroupMessage")) {
            message.setGroupMessage((Boolean) payload.get("isGroupMessage"));
        }

        // 文件相关字段
        if (payload.containsKey("fileName")) {
            message.setFileName((String) payload.get("fileName"));
        }
        if (payload.containsKey("fileSize")) {
            message.setFileSize((String) payload.get("fileSize"));
        }
        if (payload.containsKey("isFile")) {
            message.setFileMessage((Boolean) payload.get("isFile"));
        }

        return chatMessageService.saveMessage(message);
    }

    @GetMapping("/{userId}")
    public List<ChatMessage> getMessagesForUser(@PathVariable String userId) {
        return chatMessageService.getRecentMessagesForUser(userId);
    }

    @GetMapping("/group")
    public List<ChatMessage> getGroupMessages() {
        return chatMessageService.getGroupMessages();
    }

    @GetMapping("/file")
    public List<ChatMessage> getFileMessages() {
        return chatMessageService.getFileMessages();
    }
}